package com.pf.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pf.dto.BusinessReq;
import com.pf.dto.FileDTO;
import com.pf.helper.CustomFileHelper;
import com.pf.mapper.BusinessFileMapper;
import com.pf.mapper.FileMapper;
import com.pf.mapper.entity.BusinessFile;
import com.pf.mapper.entity.FileEntity;
import com.pf.service.BusinessFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2022/7/1 23:25
 */
@Service
public class BusinessFileServiceImpl implements BusinessFileService {

    @Autowired
    private CustomFileHelper customFileHelper;

    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private BusinessFileMapper businessFileMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void operation(BusinessReq businessReq) throws Exception {

        FileDTO fileDTO = customFileHelper.confirmUploadFile(businessReq.getFileId(), businessReq.getFileName());
        // 记录业务数据
        BusinessFile businessFile = BusinessFile.builder()
                .businessCode(IdUtil.fastSimpleUUID())
                .businessName(businessReq.getBusinessName())
                .fileId(fileDTO.getFileId())
                .build();
        businessFileMapper.insert(businessFile);

        // 记录附件信息
        FileEntity fileEntity = FileEntity.builder()
                .fileId(fileDTO.getFileId())
                .fileName(fileDTO.getFileName())
                .fileSize(fileDTO.getFileSize())
                .fileDownloadUrl(fileDTO.getDownloadUrl())
                .build();
        fileMapper.insert(fileEntity);
    }

    @Override
    public List<FileDTO> getFileList(String businessCode) {
        List<BusinessFile> businessFiles = businessFileMapper.selectList(new LambdaQueryWrapper<BusinessFile>()
                .eq(BusinessFile::getBusinessCode, businessCode)
        );
        List<String> fileIds = businessFiles.stream().map(BusinessFile::getFileId).collect(Collectors.toList());
        List<FileEntity> files = fileMapper.selectList(new LambdaQueryWrapper<FileEntity>()
                .in(FileEntity::getFileId, fileIds)
        );
        List<FileDTO> targetFiles = files.stream().map(file -> FileDTO.builder()
                .fileId(file.getFileId())
                .fileName(file.getFileName())
                .fileSize(file.getFileSize())
                .downloadUrl(file.getFileDownloadUrl())
                .build()
        ).collect(Collectors.toList());
        return targetFiles;
    }
}
